package com.tanhua.server.service;

import com.tanhua.autoconfig.template.ApiTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoServer {
    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private ApiTemplate apiTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto,Long id) throws IOException {
        //1.上传图片到阿里云OSS
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2.调用百度云判断是否包含人脸
        boolean detect = apiTemplate.detect(imageUrl);
        //3.不包含人脸，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //4.包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Long.valueOf(id));
            userInfo.setAvatar(imageUrl); //头像的连接
            userInfoApi.update(userInfo);
        }

    }

    /**
     * 根据ID查询用户资料
     *
     * @param userID
     * @return
     */
    public UserInfoVo findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo); //copy同名、同类型的属性
        //避免空指针判断
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString()); //因为年龄类型不同 所以要手动赋值
        }
        return userInfoVo;
    }

    /**
     * 更新用户资料
     *
     * @param userInfo
     */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
